package cn.wolfcode.p2p.job;

import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.bussness.domain.BidRequest;
import cn.wolfcode.p2p.bussness.service.IBidRequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;

//定时发布
@Component
public class BidRequestScheduledJob implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private IBidRequestService bidRequestService;

    //上锁多线程
    private ConcurrentLinkedQueue<BidRequest> bidRequestsQueue = new ConcurrentLinkedQueue<>();

    //监听对象
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        //在服务器启动的时候 先扫描一次这个方法
        queryBidRequestJob();
    }

    //每隔一小小时扫描一次
    @Scheduled(cron = "0 0 0/1 * * ?")
    public void queryBidRequestJob(){
        //查询最近的一个小时发布的借款 存入内存中
        List<BidRequest> bidRequests = bidRequestService.queryPublishPendngBidInOneHourRequest();
        for (BidRequest bidRequest : bidRequests) {
            //把所有查询出来的借款数据 放入到集合内存中
            bidRequestsQueue.add(bidRequest);
        }
        System.out.println("执行数据: " + bidRequestsQueue);
    }

    //每隔一分钟扫描一次bidRequestsQueue集合
    @Scheduled(cron = "0 0/1 * * * ?")
    public void changeBidRequestStateJob(){
        System.out.println("执行数据: " + bidRequestsQueue);
        Date now = new Date();
        //迭代集合
        Iterator<BidRequest> iterator = bidRequestsQueue.iterator();
        BidRequest bidRequest;
        while (iterator.hasNext()){
            bidRequest = iterator.next();
            //如果当前时间 大于 发布时间 就把状态修改成 招标状态
            if((now.getTime() - bidRequest.getPublishTime().getTime()) >= 0){
                //已经到时间了 修改成招标状态
                bidRequest.setBidRequestState(Constants.BIDREQUEST_STATE_BIDDING);
                //并且把这个元素 从集合中删除
                iterator.remove();
                //更新bidRequest到数据库中
                bidRequestService.update(bidRequest);
            }
        }
    }
}
